///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
#include <Shader/ShaderManager.h>
#include <Shader/GPUProgram.h>
#include <Shader/CgProgram.h>
#include <Shader/GLSLProgram.h>
#include <File/LocalFile.h>
#include <tinyxml.h>

//-----------------------------------------------------------------------------

ShaderManager::ShaderManager()
{
	m_shaders.clear();
}

//-----------------------------------------------------------------------------

ShaderManager::~ShaderManager()
{
	ReleaseShaders();
}

//-----------------------------------------------------------------------------

void	ShaderManager::ReleaseShaders()
{
	std::vector<GPUProgram*>::iterator iter;
	for( iter = m_shaders.begin(); iter != m_shaders.end(); iter++ )
	{
		SAFE_DEL( *iter );
	}
}

//-----------------------------------------------------------------------------

void	ShaderManager::AddShader(GPUProgram* shader)
{
	m_shaders.push_back( shader );
}

//-----------------------------------------------------------------------------

GPUProgram*	ShaderManager::GetShader(std::string filename)
{
	//see if already loaded
	std::vector<GPUProgram*>::iterator iter;
	for( iter = m_shaders.begin(); iter != m_shaders.end(); iter++ )
	{
		if( (*iter)->IsThisShader(filename) )
		{
			return *iter;
		}
	}

	DEBUG_ERR("[ShaderManager] Could not find '%s' shader!\n", filename.c_str() );

	return NULL;
}

//-----------------------------------------------------------------------------

void		ShaderManager::ParseElement(TiXmlElement* elem)
{
	if( elem )
	{
		ASSERT( !strcmp( elem->Value(), "shaders" )  );

		TiXmlElement* node = NULL;

		node = elem->FirstChildElement( "shader" );
		while( node )
		{
			std::string name = node->Attribute( "name" );
			std::string type = node->Attribute( "type" );

			GPUProgram *shader = NULL;

			if( type == "glsl" )
			{
				shader = MGL_NEW GLSLProgram();
			}
			else if( type == "cg" )
			{
				shader = MGL_NEW CgProgram();
			}
			else
			{
				continue;
			}

			shader->SetFilename( name );
			shader->ParseElement( node );

			AddShader( shader );

			node = node->NextSiblingElement( "shader" );
		}
	}
}

//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
